/**
 *	\file MyObserver.m
 *  
 *  \section desc_sec Description
 *  Description
 *  
 *  \if copyright
 *  	Copyright 2008 Ben Chen. All rights reserved.
 *  \endif
 *  
 *  \section hist_sec Change History:
 *  	-	3/4/08		BC		Created this file
 *  
 *  <hr>
 *  \addtogroup AKAnimationUtility
 *  @{
 */

#import "MyAppDelegate.h"

@interface MyAppDelegate ()
@property (readwrite, assign) id model;
@property (readwrite, assign) NSManagedObjectContext *managedObjectContext;
@end

@implementation MyAppDelegate

@synthesize model, managedObjectContext;

- (void) setModelUsingContext:(NSManagedObjectContext*)context {
	
	if (context) {
		self.managedObjectContext = context;
		
		NSFetchRequest *newRequest = [[NSFetchRequest alloc] init];
		[newRequest setEntity:[NSEntityDescription entityForName:@"AnimationData"
										  inManagedObjectContext:context]];
		
		NSError *error = nil;
		NSArray *result = [context executeFetchRequest:newRequest error:&error];
		
		if (result != nil) {
			if ([result count]) {
				NSLog(@"YES");
				self.model = [result objectAtIndex:0];
			}
			else
				self.model = nil;
		}	
	} else {
		self.managedObjectContext	= nil;
		self.model					= nil;
	}
}

- (void) applicationDidFinishLaunching:(NSNotification *)aNotification {
	
	NSLog(@"finish launching:%@", [NSApp orderedDocuments]);
	NSLog(@"current document:%@", [[NSDocumentController sharedDocumentController] currentDocument]);
	NSLog(@"context:%@", [[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext]);
	NSManagedObjectContext *context = [[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
	[self setModelUsingContext:context];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(windowBecomeMain:)
												 name:NSWindowDidBecomeMainNotification
											   object:nil];
}

- (void)applicationDidBecomeActive:(NSNotification *)aNotification {
	
	NSLog(@"active:%@", [NSApp orderedDocuments]);
	NSLog(@"current document:%@", [[NSDocumentController sharedDocumentController] currentDocument]);
	NSLog(@"context:%@", [[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext]);
	[self setModelUsingContext:[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext]];
}

- (void) dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super dealloc];
}

- (void) windowBecomeMain:(NSNotification*)aNotification {
	
	NSWindow *newMainWindow = [aNotification object];
	NSManagedObjectContext *context = [[[newMainWindow windowController] document] managedObjectContext];
	
	[self setModelUsingContext:context];
}

@end

/** @} */
